package com.study.util;

import java.util.HashMap;
import java.util.Map;

import com.github.pagehelper.Page;
import com.study.entity.common.CommonResponseEntity;
import com.study.enumeration.ResponseEnum;
import com.study.exception.DefinitionException;

public class ResponseUtil {

	/**
	 * 成功返回
	 * 
	 * @param <T>
	 * @param data 返回数据
	 * @return
	 */
	public static <T> CommonResponseEntity<T> success(T data) {
		CommonResponseEntity<T> resp = new CommonResponseEntity<>();
		resp.setCode(ResponseEnum.SUCCESS.getCode());
		resp.setMsg(ResponseEnum.SUCCESS.getMsg());
		resp.setData(data);
		return resp;
	}

	/**
	 * 成功返回，无数据
	 * 
	 * @param <T>
	 * @return
	 */
	public static <T> CommonResponseEntity<T> success() {
		return success(null);
	}

	/**
	 * 失败返回
	 * 
	 * @param <T>
	 * @param responseEnum 响应标识
	 * @return
	 */
	public static <T> CommonResponseEntity<T> error(ResponseEnum responseEnum) {
		CommonResponseEntity<T> resp = new CommonResponseEntity<>();
		resp.setCode(responseEnum.getCode());
		resp.setMsg(responseEnum.getMsg());
		return resp;
	}

	/**
	 * 其他异常处理方法返回的结果
	 * 
	 * @param responseEnum 自定义枚举类，包含 code 和 message
	 * @return 返回其他异常
	 */
	public static CommonResponseEntity<Object> otherError(ResponseEnum responseEnum) {
		return new CommonResponseEntity<>(responseEnum);
	}

	/**
	 * 自定义异常返回的结果
	 * 
	 * @param ex 自定义异常处理类
	 * @return 返回自定义异常
	 */
	public static CommonResponseEntity<Object> defineError(DefinitionException ex) {
		return new CommonResponseEntity<Object>(ex.getErrorCode(), ex.getErrorMsg());
	}

	/**
	 * 构建分页查询的返回结果
	 * 
	 * @param page
	 * @return
	 */
	public static CommonResponseEntity<Map<String, Object>> buildPage(Page<?> page) {
		HashMap<String, Object> data = new HashMap<>();
		data.put("count", page.getTotal());
		data.put("records", page.getResult());
		return ResponseUtil.success(data);
	}

	/**
	 * 成功或失败的响应信息
	 * 
	 * @param success
	 * @return
	 */
	public static CommonResponseEntity<Object> buildResult(boolean success) {
		if (success) {
			return ResponseUtil.success();
		}
		return ResponseUtil.error(ResponseEnum.OPR_FAIL);
	}

}
